package cn.core.tool.aspect;

import cn.core.tool.context.CoreContextData;
import cn.core.tool.eo.DataManipulationLog;
import cn.core.tool.mapper.CoreMapper;
import cn.core.tool.util.CoreTool;
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Mapper AOP 拦截器 >>> 删除
 */
@Log4j2
@Aspect
@Component
@ConditionalOnProperty(prefix = "proconf", name = "mapper-aspect-remove", havingValue = "true")
public class MapperAspectRemove {

  @Resource
  private CoreMapper coreMapper;

  @Resource
  private Gson gson;

  @Pointcut("execution(public * cn.core..mapper..*.remove(..))")
  public void remove() {
  }

  @SuppressWarnings("Duplicates")
  @AfterReturning("remove()")
  public void doAfterReturning(JoinPoint joinPoint) throws Exception {
    try {
      for (Object o : joinPoint.getArgs()) {
        if (o != null) {
          DataManipulationLog saveDataManipulationLog = new DataManipulationLog()
              .setId(CoreTool.getUUID32())
              .setOperationMethod("remove")
              .setNexusType(CoreContextData.getCurrentContextData() != null ? CoreContextData.getCurrentContextData().getNexusType() : null)
              .setOperationId(CoreContextData.getCurrentContextData() != null ? CoreContextData.getCurrentContextData().getUsrId() : null)
              .setOperationAid(CoreContextData.getCurrentContextData() != null ? CoreContextData.getCurrentContextData().getAccountId() : null)
              .setOperationName(CoreContextData.getCurrentContextData() != null ? CoreContextData.getCurrentContextData().getUsrname() : null)
              .setOperationTimes(System.currentTimeMillis())
              .setDataObjectClassName(o.getClass().getName())
              .setDataContent(gson.toJson(o));
          try {
            saveDataManipulationLog.setDataId((String) o.getClass().getMethod("getId").invoke(o));
          } catch (NoSuchMethodException e) {
          }
          coreMapper.saveDataManipulationLog(saveDataManipulationLog);
        }
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
